package com.orange.common.popup

import androidx.lifecycle.Lifecycle
import com.lxj.xpopup.core.BasePopupView
import com.orange.common.ktx.doOnDestroy

/**
 * Created by Orange on 2022/11/13 14:55.
 * Popup弹窗管理 用于连续按顺序弹出
 */
class PopupManage private constructor(lifecycle: Lifecycle){

    companion object {

        private val POPUP_MANAGER: HashMap<Lifecycle, PopupManage> = HashMap()

        fun getInstance(lifecycle: Lifecycle): PopupManage {

            var manager: PopupManage? = POPUP_MANAGER[lifecycle]
            if (manager == null) {
                manager = PopupManage(lifecycle)
                POPUP_MANAGER[lifecycle] = manager
            }
            return manager
        }

    }

    private val popups: MutableList<BasePopupView> = mutableListOf()

    init {
        lifecycle.doOnDestroy {
            POPUP_MANAGER.remove(lifecycle)
            clearShow()
        }
    }

    /**
     * 排队显示 Dialog
     */
    fun addShow(popup: BasePopupView) {
        if (popup.isShow) {
            throw IllegalStateException("此弹窗已经在显示中了")
        }
        // 禁止同一个弹窗 重复添加
        if (popups.contains(popup)) {
            return
        }
        popups.add(popup)
        val firstDialog: BasePopupView = popups[0]
        if (!firstDialog.isShow) {
            firstDialog.show()
        }
    }

    /**
     * 显示下一个
     */
    fun showNext(popup: BasePopupView?) {
        remove(popup)
        for (nextPopup: BasePopupView in popups) {
            if (!nextPopup.isShow) {
                nextPopup.show()
                break
            }
        }
    }

    /**
     * 从队列中移除
     */
    fun remove(popup: BasePopupView?) {
        popups.remove(popup)
    }

    /**
     * 取消所有 Dialog 的显示
     */
    fun clearShow() {
        if (popups.isEmpty()) {
            return
        }
        popups.clear()
    }

}